import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home'),
    // component: () => import('@/views/Login'),
  },
  {
    path: '/shopcart1',
    name: 'ShopCart1',
    component: () => import('@/views/ShopCart1'),
  },
  {
    path: '/pay',
    name: 'Pay',
    component: () => import('@/views/Pay'),
  },
  {
    path: '/topay',
    name: 'Topay',
    component: () => import('@/views/Topay'),
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('@/views/Search'),
  },
  {
    path: '/detail',
    name: 'Detail',
    component: () => import('@/views/Detail'),
  },
  {
    path: '/newgoods',
    name: 'NewGoods',
    component: () => import('@/views/NewGoods'),
  },
  {
    path: '/item',
    name: 'Item',
    component: () => import('@/views/item'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register'),
  },
  {
    path: '/logintest',
    name: 'Logintest',
    component: () => import('@/views/Login-test'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  // 页面跳转时,让页面滚动条滚动到顶部
  scrollBehavior() {
    return { x: 0, y: 0 }
  },
})

// 设置白名单
const whiteList = [
  'Home',
  'Search',
  'Detail',
  'NewGoods',
  'Item',
  'Login',
  'Register',
]

// router.beforeEach((to, from, next) => {
//   // 判断是否在白名单中-->没有把login添加进白名单的时候
//   // 判断是否有token
//   const token = store.state.user.token
//   if (whiteList.includes(to.name) || token) {
//     // 在白名单中或者有token,直接跳
//     next()
//     return
//   } else {
//     if (to.path === '/login' && !token) {
//       //去的页面是login,并且没有token,直接去
//       next()
//     } else {
//       // 去的不是login页面并且没有token
//       next('/login')
//     }
//   }
// })

router.beforeEach((to, from, next) => {
  // 判断是否在白名单中-->白名单中有login
  // 判断是否有token
  if (whiteList.includes(to.name) || store.state.user.token) {
    next()
    return
  } else {
    next({
      name: 'Login',
      query: {
        redirect: to.path,
      },
    })
    return
  }
  // 不在白名单中,也没有token的,要跳转到login先登录,登录后跳转回原来的页面
})

export default router
